<template>
    <div class="app-container">
        <el-divider content-position="left">编辑学工活动内容</el-divider>
        <!-- <label>发布后各个班级的班主任或学生可以查看。</label> -->
        <el-form ref="form" :model="safeFormData" label-width="110px" :rules="rules"  :loading="loading">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="safeFormData.title" style="width:80%"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="通知类型" prop="title">
                        <el-select v-model="safeFormData.noticeType" @change="selectScope" :disabled="true">
                            <el-option label="学工活动通知" value="0"></el-option>
                            <!-- <el-option label="违纪通知" value="2"></el-option> -->
                            <!-- <el-option label="安全通知" value="1"></el-option> -->
                        </el-select>
                    </el-form-item>
                </el-col>
                
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="发布范围" prop="releaseScopeNotice">
                        <el-select v-model="safeFormData.releaseScopeNotice" @change="selectScope">
                            <el-option label="班级" value="1"></el-option>
                            <el-option label="年级" value="2"></el-option>
                            <el-option label="全校" value="3"></el-option>

                        </el-select>
                        <!--班级-->
                        <el-select v-if="safeFormData.releaseScopeNotice==1" multiple collapse-tags v-model="safeFormData.classIds" placeholder="输入班级" clearable>
                            <el-option v-for="item in classList" :label="item.className" :value="item.id+''" :key="item.id"></el-option>
                        </el-select>
                        <!--年级-->
                        <el-select v-if="safeFormData.releaseScopeNotice==2" v-model="safeFormData.grade">
                            <el-option v-for="item in gradeList" :key="item.id" :label="item.dictLabel+''" :value="item.dictValue+''"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否通知学生" >
                        <el-radio v-model="safeFormData.isNoticeStudent" label="1">是</el-radio>
                        <el-radio v-model="safeFormData.isNoticeStudent" label="0">否</el-radio>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="是否通知部门" >
                        <el-radio v-model="safeFormData.isNoticeDept" label="1">是</el-radio>
                        <el-radio v-model="safeFormData.isNoticeDept" label="0">否</el-radio>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="选择通知部门" >
                        <el-cascader style="width:60%;" @change="changeDept" v-model="safeFormData.noticeDeptList" 
                        :options="deptOptions"
                        :props="props"
                        clearable></el-cascader>
                    </el-form-item>
                </el-col>
                
            </el-row>
            <!-- <el-row>
                <el-col :span="12">
                    <el-form-item label="是否立即发送" prop="isSend">
                        <el-radio v-model="safeFormData.isSend" label="1">是</el-radio>
                        <el-radio v-model="safeFormData.isSend" label="0">否</el-radio>
                    </el-form-item>
                </el-col>
            </el-row> -->
            <el-form-item label="内容" prop="noticeContent">
                <quill-editor 
                    v-model="safeFormData.noticeContent"
                    ref="myQuillEditor"
                    :options="editorOption"
                >
                </quill-editor>
            </el-form-item>
            
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center; margin-top: 20px;">
            <el-button type="warning" @click="viewContent" icon="el-icon-search" size="mini" :loading="loading">预 览</el-button>
            <el-button type="primary" @click="submitForm" icon="el-icon-check" size="mini" :loading="loading">提 交</el-button>
            <el-button @click="cancel" size="mini" icon="el-icon-close">取 消</el-button>
        </div>

        <!--预览-->
        <el-dialog title="预览" :visible.sync="open" width="40%" >
            <el-divider content-position="center">
                <el-select size="mini" v-model="selectModelData" placeholder="选择机型" @change="selectModel">
                    <el-option label="IPhoneSE" value="375,667" ></el-option>
                    <el-option label="IPhoneXR" value="414,896"></el-option>
                    <el-option label="IPhone12 PRO" value="390,844"></el-option>
                    <el-option label="Pixel 5" value="393,851"></el-option>
                    <el-option label="Galaxy Fold" value="280,653"></el-option>
                </el-select>
            </el-divider>
            <div>
                <div class="modelDiv" :style="modelStyle">
                    <div  style="text-align: center;"><h2>{{viewData.title}}</h2></div>
                    <div v-html="viewData.context"></div>
                </div>
            </div>
            
        </el-dialog>
    </div>
  </template>
  
<script>
import  {quillEditor}  from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { listTermtime } from "@/api/system/termtime.js";
import { addOrUpdateEntranceProcess , findEntranceProcessDetailById} from "@/api/studentInfo/entranceProcess";
import { addNoticeSchool,updateNoticeSchool,getNoticeSchool} from "@/api/notice/schoolNotice";
import { findAllSchoolClass } from "@/api/studentInfo/infoMaintenance/index";
import { treeselectAll } from "@/api/system/dept";

  
  export default {
    name: "entranceEdit",
    components: {quillEditor},
    data() {
        var validatePass = (rule, value, callback) => {
            debugger
            if(this.safeFormData.releaseScopeNotice==1 && (!this.safeFormData.classIds || this.safeFormData.classIds.length<1)){
                callback(new Error('请选择班级'));
            }
            if (this.safeFormData.releaseScopeNotice==2 && !this.safeFormData.grade) {
                callback(new Error('请选择年级'));
            } else {
            // this.$refs['leaveFormData'].clearValidate(['leaveStartTime','leaveEndTime'])
                callback();
            }
        };
      return {
        open:false,
        // 遮罩层
        loading: false,
        safeFormData:{
            title:undefined,
            noticeType:'0',
            context:undefined,
            status:"1"
        },
        viewData:{},
        // 编辑器配置
        editorOption: {
            placeholder: '在这里输入内容',
            modules: {
            toolbar: [
                ['bold', 'italic', 'underline', 'strike'], //  加粗、倾斜、下划线、删除线
                ['blockquote', 'code-block'],// 引用代码块
                [{'header': 1}, {'header': 2}], // 标题，键值对应的形式，1，2 表示字体大小
                [{'list': 'ordered'}, {'list': 'bullet'}], // 列表
                [{'script': 'sub'}, {'script': 'super'}], // 上下标
                [{'indent': -1}, {'indent': +1}], // 缩进
                [{'direction': 'rtl'}], // 文本方向
                [{'size': ['small', false, 'large', 'huge']}], // 字体大小
                [{'header': [1, 2, 3, 4, 5, 6, false]}], // 几级标题
                [{'color': []}, {'background': []}], // 字体颜色，字体背景颜色
                [{'font': []}], // 字体
                [{'align': []}], // 对齐方式
                ['clean'], //清除
                ['image', 'video'], // 上传图片、上传视频
            ]
            }
        },
        termTimeList:[],
        rules:{
            title:[{ required: true, message: "请填写标题", trigger: "blur" }],
            releaseScopeNotice:[{ required: true, message: "请选择发布范围", trigger: "blur" },
            { validator: validatePass, trigger: 'blur' }],
            noticeContent:[
                { required: true, message: "请编辑迎新内容", trigger: "blur" }
                
            ],
            isSend:[{ required: true, message: "请选择是否立即发送", trigger: "blur" }]
        },
        modelStyle: {
                width:'375px',
                height:'667px',
                overflow: 'auto'
            },
        selectModelData:'375,667',
        gradeList:[],
        classList:[],
        id:null,
        deptOptions:[],
        props:{multiple: true},
      };
    },
    mounted() {
        let content = ''; // 请求返回值
        this.str = this.escapeStringHTML(content)
    },
    computed: {
        editor() {
        return this.$refs.myQuillEditor.quill
        }
    },
    created() {
        this.getTreeselect()
        this.getTermTimeList()
        const paramId = this.$route.query.id
        this.id = this.$route.query.id

        if(paramId){
            this.loading=true
            getNoticeSchool(paramId).then(resp=>{
                this.safeFormData = resp.data
                this.safeFormData.noticeType = resp.data.noticeType+''
                this.safeFormData.noticeDeptList = JSON.parse(this.safeFormData.noticeDepts)
                this.selectScope(this.safeFormData.releaseScopeNotice)
                if(this.safeFormData.classIds){}
                this.loading=false
            })
        }
    },
    methods: {
        changeDept(item){
            console.log(item)
            if(item.length>0){
                let depts = []
                for(let i=0;i<item.length;i++){
                    depts.push(item[i].join(','))
                }

            }
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselectAll().then(response => {
                this.deptOptions = response.data;
            });
        },
        selectScope(val){
            if(val==1){//查询有效的班级
                this.getClassList()
            }
            if(val==2){//查询有效的班级
                this.getDicts("class_grade").then(response => {
                    this.gradeList = response.data;
                });
            }
            
        },
        getClassList(){
            findAllSchoolClass().then(resp=>{
                this.classList = resp.data
            })
        },
        // 转码
        escapeStringHTML(str) {
            str = str.replace(/</g, '<');
            str = str.replace(/>/g, '>');
            return str
        },
        onclickForm() {
            console.log(this.content)
            this.content = ''
        },
        getTermTimeList() {
            //查询学期
            // this.loading = true;
            listTermtime({pageSize:100,pageNum:1,status:1}).then(response => {
                this.termTimeList = response.data.list;
            });
        },
        submitForm(){
            const _this = this
            console.log(this.safeFormData)
            if(this.safeFormData.isNoticeDept=='1' && (!this.safeFormData.noticeDeptList || this.safeFormData.noticeDeptList.length==0)){
                this.$message({
                        message: '请选择通知部门',
                        type: 'warning'
                    });
                return
            }

            this.safeFormData.noticeDepts = JSON.stringify(this.safeFormData.noticeDeptList)
            this.loading = true
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if(this.id){
                        updateNoticeSchool(this.safeFormData).then(resp=>{
                            this.loading = false
                            this.$confirm('更新成功，是否停留在该页面', "警告", {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "success"
                            }).then(() => {
                                _this.reset()
                            }).catch(function() {
                                _this.$router.push("/studentManagement/play")
                            });
                        })
                    }else{
                        addNoticeSchool(this.safeFormData).then(resp=>{
                            this.loading = false
                            this.$confirm('提交成功，是否停留在该页面', "警告", {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "success"
                            }).then(() => {
                                _this.reset()
                            }).catch(function() {
                                _this.$router.push("/studentManagement/play")
                            });
                        })
                    }
                    
                }else{
                    this.loading = false
                }
            })
        },
        cancel(){
            this.$router.push("/studentManagement/play")
        },
        reset(){
            this.safeFormData={
                title:undefined,
                semester:undefined,
                context:undefined,
                status:"1"
            }
        },
        viewContent(){
            this.open=true
            this.viewData = this.safeFormData
            const context = this.safeFormData.noticeContent.replace(/<img/gi,"<img width='100%'")
            this.viewData.context = context

        },
        selectModel(val){
            alert(val)
            const items = val.split(',')
            this.modelStyle = {
                width:items[0]+'px',
                height:items[1]+'px',
                overflow: 'auto'
            }


        }
    }
  };
  </script>
<style scoped lang="scss">
  ::v-deep .ql-editor {
    min-height: 300px;
  }

  .modelDiv{
    border: 1px solid rgb(112, 111, 111);
    margin: 0 auto; 
    border-radius: 5px;
    
  } 
</style>